import { Controller, Get, Param, Post, Res, UploadedFiles, UseInterceptors } from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';
import { writeFileSync } from 'fs';
import { join } from 'path';
import { cwd } from 'process';
import { build } from "node-xlsx"
import { Files2xlsxService } from './files2xlsx.service';
import { Response } from 'express';


const root = cwd()
const assets = join(root, "assets")
const resDir = join(assets, "result")
@Controller('files2xlsx')
export class Files2xlsxController {
    constructor(
        private readonly service: Files2xlsxService
    ) { }

    @Post("upload")
    @UseInterceptors(FilesInterceptor('files'))
    uploadFile(@UploadedFiles() files: Array<Express.Multer.File>) {
        const data = [];
        for (const file of files) {
            file.originalname = Buffer.from(file.originalname, 'latin1').toString('utf8');
            const txt = file.buffer.toString("utf8");
            data.push([file.originalname, txt])
        }
        const name = `${Date.now()}.xlsx`
        const path = join(resDir, name);
        writeFileSync(path, build([{
            name: "",
            data,
            options: {}
        }]))
        return name;
    }

    @Get(":name/download")
    download(
        @Param("name") name: string,
        @Res() res: Response
    ) {
        const filePath = join(resDir, name);
        res.sendFile(filePath)
    }
}
